// src/components/scholarDashboard/mainContent/Table.tsx

import { useState, useEffect } from "react";
import { LuPanelRightClose, LuPanelRightOpen } from "react-icons/lu";
import { MdSentimentDissatisfied } from "react-icons/md";
import type { ScholarRecordWithFullName } from "@/services/scholarsDashboardService/tableScholarRecords";

const formatDateForDisplay = (dateString: string | null): string => {
  if (!dateString) return '';
  try {
    const date = new Date(dateString);
    if (isNaN(date.getTime())) return '';
    return date.toLocaleDateString('en-GB', {
      day: '2-digit',
      month: '2-digit',
      year: 'numeric'
    });
  } catch {
    return '';
  }
};

interface TableProps {
  scholars: ScholarRecordWithFullName[];
  onTotalColumnsChange?: (total: number) => void;
  selectedHeaders: string[];
}

interface TableHeader {
  label: string;
  key: keyof ScholarRecordWithFullName;
  expandable?: boolean;
  expanded?: boolean;
  children?: TableHeader[];
}

const Table = ({
  scholars,
  onTotalColumnsChange,
  selectedHeaders,
}: TableProps) => {
  const [headers, setHeaders] = useState<TableHeader[]>([
    { label: "Student Number", key: "student_number" },
    { label: "Program ID", key: "program" },
    {
      label: "Full Name",
      key: "full_name",
      expandable: true,
      expanded: false,
      children: [
        { label: "Preferred Name", key: "preferred_name" },
      ],
    },
    {
      label: "Student Email",
      key: "default_email",
      expandable: true,
      expanded: false,
      children: [
        { label: "Alternate Email", key: "alternate_email" },
      ],
    },
    { label: "Scholar Type", key: "scholar_type" },
    { label: "Year", key: "year" },
    { label: "University Status", key: "university_status" },
    { label: "Date of Birth", key: "date_of_birth" },
    { label: "Gender", key: "gender" },
    { label: "School Code", key: "school_code" },
    { label: "School Name", key: "school_name" },
    { label: "Gateway School", key: "gateway_school" },
    { label: "Indigenous Student", key: "indigenous_student" },
    { label: "Start Date", key: "start_date" },
    { label: "End Date", key: "end_date" },
    { label: "Dietary Preference", key: "dietary_preference" },
    { label: "Dietary Allergies", key: "dietary_allergies" },
    { label: "Dietary Religious", key: "dietary_religious" },
    { label: "Medical Allergies", key: "medical_allergies" },
    { label: "ITE Number", key: "ite_number" },
    { label: "Sponsor Name", key: "sponsor_name" },
    { label: "Department", key: "department" },
    { label: "Supervisors", key: "supervisors" },
    { label: "ITE Start", key: "ite_start" },
    { label: "ITE End", key: "ite_end" },
    { label: "ITE Details Input Date", key: "ite_details_input_date" },
    { label: "ITE Input In Time", key: "ite_input_in_time" },
    { label: "Latest Start Date", key: "latest_start_date" },
    { label: "Expected Finish Date", key: "expected_finish_date" },
    { label: "Start Date Met", key: "start_date_met" },
    { label: "End Date Met", key: "end_date_met" },
    { label: "IT Change Approved", key: "it_change_approved" },
    { label: "PD Agreement Submission Date", key: "pd_agreement_submission_date" },
    // { label: "PD Submitted On Time", key: "pd_submitted_on_time" },
    { label: "Placement Mid Point", key: "placement_mid_point" },
    { label: "MPC Call Date", key: "mpc_call_date" },
    { label: "MPC Call On Time", key: "mpc_call_on_time" },
    { label: "MPC Document Due Date", key: "mpc_document_due_date" },
    { label: "MPC Submitted Date", key: "mpc_submitted_date" },
    { label: "MPC Submitted On Time", key: "mpc_submitted_on_time" },
    { label: "End of IT Presentation Date", key: "end_of_it_presentation_date" },
    { label: "End of IT Input Date", key: "end_of_it_input_date" },
    { label: "IT Presentation Completed On Time", key: "it_presentation_completed_ontime" },
    { label: "UNSW Attendee On Presentation", key: "unsw_attendee_on_presentation" },
    { label: "Sponsor Evaluation Sent To Sponsor Date", key: "sponsor_evaluation_sent_to_sponsor_date" },
    { label: "Sent Before End of Placement", key: "sent_before_end_of_placement" },
    { label: "Sponsor Completed Date", key: "sponsor_completed_date" },
    { label: "Scholar Comment", key: "scholar_comment" },
    { label: "Sponsor Evaluation Completed On Time", key: "sponsor_evaluation_completed_on_time" },
    { label: "Placement Completed Date", key: "placement_completed_date" },
    { label: "Placement Grade", key: "placement_grade" },
    { label: "Placement Performance", key: "placement_performance" },
    { label: "Grade Updated", key: "grade_updated" },
    { label: "Grade Updated Date", key: "grade_updated_date" },
  ]);

  const toggleExpand = (index: number) => {
    const newHeaders = [...headers];
    const header = newHeaders[index];
    if (header.expandable) {
      header.expanded = !header.expanded;
      setHeaders(newHeaders);
    }
  };

  const flatHeaders: TableHeader[] = headers.flatMap((header) => {
    if (header.expandable && header.expanded && header.children) {
      return [header, ...header.children];
    }
    return [header];
  });

  const filteredHeaders = flatHeaders.filter((header) =>
    selectedHeaders.includes(header.key as string)
  );

  useEffect(() => {
    onTotalColumnsChange?.(filteredHeaders.length);
  }, [filteredHeaders.length, onTotalColumnsChange]);

  return (
    <div className="overflow-x-auto mt-4 px-1 sm:px-4 font-poppins w-full">
      <div className="bg-white dark:bg-slate-800 rounded-2xl shadow-md overflow-hidden border border-gray-200 dark:border-slate-700 min-h-[200px] flex items-center justify-center w-full transition-all duration-300">
        {filteredHeaders.length === 0 ? (
          <div className="flex flex-col items-center justify-center w-full py-16 text-gray-400 dark:text-gray-500">
            <span className="text-5xl mb-4 text-blue-200 dark:text-cyan-900"><MdSentimentDissatisfied /></span>
            <span className="italic text-xs sm:text-sm md:text-base text-center">Please select one or more columns to display.</span>
          </div>
        ) : (
          <div className="overflow-x-auto w-full">
            <table className="w-full text-xs sm:text-sm md:text-base border-b border-gray-100 dark:border-slate-700">
              <thead className="sticky top-0 z-10 bg-blue-50 dark:bg-slate-800 border-b-2 border-gray-200 dark:border-slate-700 shadow-sm text-xs sm:text-sm md:text-base transition-all duration-300">
                <tr>
                  {filteredHeaders.map((header, idx) => {
                    const parent = headers.find(
                      (h) =>
                        h.children?.some((child) => child.key === header.key) &&
                        h.expanded
                    );
                    const childKeys = parent?.children?.map((c) => c.key) ?? [];
                    const isLeft = header.key === childKeys[0];
                    const isRight = header.key === childKeys[childKeys.length - 1];
                    const isInside = !!parent;

                    const borderClasses = isInside
                      ? [
                        "border-t-2",
                        "border-b-2",
                        isLeft && "border-l-2 rounded-tl-md rounded-bl-md",
                        isRight && "border-r-2 rounded-tr-md rounded-br-md",
                        "border-blue-400 dark:border-cyan-400 border-dashed",
                      ]
                        .filter(Boolean)
                        .join(" ")
                      : "border-r border-gray-200 dark:border-slate-600";

                    return (
                      <th
                        key={`${header.label}-${idx}`}
                        className={`p-2 sm:p-3 text-left font-extrabold text-gray-800 dark:text-cyan-300 whitespace-nowrap tracking-wide ${borderClasses}`}
                        aria-label={header.label}
                        title={header.label}
                      >
                        <div className="flex items-center justify-between">
                          <span>{header.label}</span>
                          {header.expandable && (
                            <button
                              onClick={() =>
                                toggleExpand(
                                  headers.findIndex((h) => h.key === header.key)
                                )
                              }
                              className="ml-2 hover:scale-125 transition-transform focus:outline-none rounded-full p-1 hover:bg-blue-100 dark:hover:bg-slate-700"
                              tabIndex={-1}
                            >
                              {header.expanded ? (
                                <LuPanelRightOpen className="text-blue-500 dark:text-cyan-300" size={18} />
                              ) : (
                                <LuPanelRightClose className="text-blue-500 dark:text-cyan-300" size={18} />
                              )}
                            </button>
                          )}
                        </div>
                      </th>
                    );
                  })}
                </tr>
              </thead>

              <tbody>
                {scholars.length === 0 ? (
                  <tr>
                    <td
                      colSpan={filteredHeaders.length}
                      className="text-center p-8 sm:p-12 text-gray-400 dark:text-gray-500 italic bg-gray-50 dark:bg-slate-900"
                    >
                      <span className="text-5xl mb-4 block text-blue-200 dark:text-cyan-900"><MdSentimentDissatisfied /></span>
                      <span className="italic text-xs sm:text-sm md:text-base text-center">No scholar records found.</span>
                    </td>
                  </tr>
                ) : (
                  scholars.map((scholar, rowIndex) => (
                    <tr
                      key={rowIndex}
                      className={"border-t border-gray-100 dark:border-slate-700 transition-all duration-150 hover:bg-blue-50/60 dark:hover:bg-slate-700/60"}
                    >
                      {filteredHeaders.map((header, colIndex) => {
                        const parent = headers.find(
                          (h) =>
                            h.children?.some((child) => child.key === header.key) &&
                            h.expanded
                        );
                        const childKeys = parent?.children?.map((c) => c.key) ?? [];
                        const isLeft = header.key === childKeys[0];
                        const isRight = header.key === childKeys[childKeys.length - 1];
                        const isInside = !!parent;

                        const cellBorderClasses = isInside
                          ? [
                            "border-t-2",
                            "border-b-2",
                            isLeft && "border-l-2",
                            isRight && "border-r-2",
                            "border-blue-400 dark:border-cyan-400 border-dashed",
                          ]
                            .filter(Boolean)
                            .join(" ")
                          : "border-r border-gray-100 dark:border-slate-700";

                        return (
                          <td
                            key={`${rowIndex}-${colIndex}`}
                            className={`p-2 sm:p-3 text-gray-800 dark:text-gray-100 whitespace-nowrap transition-colors duration-100 ${cellBorderClasses}`}
                          >
                            {header.key === 'full_name'
                              ? scholar.full_name
                              : header.key === 'ite_input_in_time'
                                ? (scholar.ite_input_in_time === true ? 'Yes' : scholar.ite_input_in_time === false ? 'No' : '')
                                : header.key === 'start_date_met'
                                  ? (scholar.start_date_met === true ? 'Yes' : scholar.start_date_met === false ? 'No' : '')
                                  : header.key === 'end_date_met'
                                    ? (scholar.end_date_met === true ? 'Yes' : scholar.end_date_met === false ? 'No' : '')
                                    // : header.key === 'pd_submitted_on_time'
                                    //   ? (scholar.pd_submitted_on_time === true ? 'Yes' : scholar.pd_submitted_on_time === false ? 'No' : '')
                                      : header.key === 'sent_before_end_of_placement'
                                        ? (scholar.sent_before_end_of_placement === true ? 'Yes' : scholar.sent_before_end_of_placement === false ? 'No' : '')
                                        : header.key === 'sponsor_evaluation_completed_on_time'
                                          ? (scholar.sponsor_evaluation_completed_on_time === true ? 'Yes' : scholar.sponsor_evaluation_completed_on_time === false ? 'No' : '')
                                          : header.key === 'date_of_birth'
                                            ? formatDateForDisplay(scholar.date_of_birth)
                                            : header.key === 'start_date'
                                              ? formatDateForDisplay(scholar.start_date)
                                              : header.key === 'end_date'
                                                ? formatDateForDisplay(scholar.end_date)
                                                : header.key === 'ite_start'
                                                  ? formatDateForDisplay(scholar.ite_start)
                                                  : header.key === 'ite_end'
                                                    ? formatDateForDisplay(scholar.ite_end)
                                                    : header.key === 'ite_details_input_date'
                                                      ? formatDateForDisplay(scholar.ite_details_input_date)
                                                      : header.key === 'latest_start_date'
                                                        ? formatDateForDisplay(scholar.latest_start_date)
                                                        : header.key === 'expected_finish_date'
                                                          ? formatDateForDisplay(scholar.expected_finish_date)
                                                          : header.key === 'pd_agreement_submission_date'
                                                            ? formatDateForDisplay(scholar.pd_agreement_submission_date)
                                                            : header.key === 'placement_mid_point'
                                                              ? formatDateForDisplay(scholar.placement_mid_point)
                                                              : header.key === 'mpc_call_date'
                                                                ? formatDateForDisplay(scholar.mpc_call_date)
                                                                : header.key === 'mpc_document_due_date'
                                                                  ? formatDateForDisplay(scholar.mpc_document_due_date)
                                                                  : header.key === 'mpc_submitted_date'
                                                                    ? formatDateForDisplay(scholar.mpc_submitted_date)
                                                                    : header.key === 'end_of_it_presentation_date'
                                                                      ? formatDateForDisplay(scholar.end_of_it_presentation_date)
                                                                      : header.key === 'end_of_it_input_date'
                                                                        ? formatDateForDisplay(scholar.end_of_it_input_date)
                                                                        : header.key === 'sponsor_evaluation_sent_to_sponsor_date'
                                                                          ? formatDateForDisplay(scholar.sponsor_evaluation_sent_to_sponsor_date)
                                                                          : header.key === 'sponsor_completed_date'
                                                                            ? formatDateForDisplay(scholar.sponsor_completed_date)
                                                                            : header.key === 'placement_completed_date'
                                                                              ? formatDateForDisplay(scholar.placement_completed_date)
                                                                              : header.key === 'grade_updated_date'
                                                                                ? formatDateForDisplay(scholar.grade_updated_date)
                                                                                : scholar[header.key as keyof ScholarRecordWithFullName] ?? ''}
                          </td>
                        );
                      })}
                    </tr>
                  ))
                )}
              </tbody>
            </table>
          </div>
        )}
      </div>
    </div>
  );
};

export default Table;